<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
// import { useIcon } from '@/hooks/web/useIcon'
import { reactive, watch } from 'vue'
import {
  goodsSelect,
  transportSelect,
  placestartSelect,
  getPayTypeList,
  clientSelect,
  storeSelect,
  consigneeSelect,
  placeendSelect
} from '@/api/common'

import {
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElCol,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElDivider
} from 'element-plus'
import { NumberFormat } from 'vue-i18n'

const { t } = useI18n()

// const addIcon = useIcon({ icon: 'gala:add' })
// const delIcon = useIcon({ icon: 'material-symbols:delete-outline' })

const props = defineProps({
  currentRow: {
    type: Object as any,
    default: () => null
  }
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    form.id = currentRow.id
    form.paymentAmountType = currentRow.paytype
    form.typeOfGoods = currentRow.goods_id
    form.locationOfGoods = currentRow.store_id
    form.modeOfTransport = currentRow.transport
    form.origin = currentRow.placestart
    form.relatedCustomers = currentRow.client_code
    form.warehousingTime = currentRow.buytime
    form.servicefee = currentRow.servicefee
    form.collectionOfFreight = currentRow.freight
    form.rebate = currentRow.rebate
    form.priceDifferenceOfGoods = currentRow.chajia
    form.productNameRemarks = currentRow.remark
    form.warehousingItems = currentRow.piece
    form.value = currentRow.worth
    form.recipient = currentRow.shouhuo
    form.destination = currentRow.placeend
    form.total_sale = currentRow.total_sale
    form.taxRate = currentRow.taxrate
    form.freight_receive = currentRow.freight_receive
    let goodsStr = currentRow.goods.replace(/&quot;/g, '"')
    let goodsArr: any = JSON.parse(goodsStr)
    console.log(goodsArr)
    goodsArr.forEach((item, i) => {
      let copyItem = JSON.parse(JSON.stringify(item))
      delete copyItem.gname
      delete copyItem.goods_id
      delete copyItem.worth
      let pieceItem = {
        key: i + 1,
        title: `${t('warehousingEntryAddWrite.goodsEntry')} ${i + 1} ：`,
        gname: item.gname, // 名称
        goods_id: item.goods_id, // 货物种类
        worth: item.worth, // 单件货值
        piece: item.piece,
        quantity: item.quantity,
        room: item.room,
        colour: item.colour,
        length: item.length,
        width: item.width,
        high: item.high,
        weight: item.weight,
        remark: item.remark,
        total: item.total,
        price: item.price
        // list: [
        //   {
        //     ...copyItem
        //   }
        // ]
      }
      form.pieceArray.push(pieceItem)
      totalSUM()
    })
  }
)

// 表单对应的字段（绑定到输入框以及选择框俄字段）
const form: any = reactive({
  id: '',
  paymentAmountType: '', //付款金额类型
  typeOfGoods: '', //货品种类
  locationOfGoods: '', //货物位置
  modeOfTransport: '', //运输方式
  origin: '', //始发地
  relatedCustomers: '', //关联客户
  // warehousingTime: '', //入库时间
  servicefee: '', //服务费
  collectionOfFreight: '', //代收运费
  rebate: '', //工厂返点
  priceDifferenceOfGoods: '', //货品差价
  productNameRemarks: '', //品名备注
  warehousingItems: '', //入库件数，
  value: '', //采购总合计,
  priceValue: '', //销售总合计
  recipient: '', // 收件人
  destination: '', // 目的地
  taxRate: '', // 税率
  pieceArray: [], //入库货物
  priceservicefee: '', //服务费金额
  pricerebate: '', //工厂返点金额
  freight_receive: '', //应收运费
  total_sale: '' //销售合计
})

// 物品的种类选项
const typeOfGoodsArr: any = reactive([])
const getGoodsSelect = async () => {
  // let goodsTypeArr: any = []
  let res: any = await goodsSelect({})
  res.data.list.forEach((item) => {
    typeOfGoodsArr.push({
      label: item.name,
      value: item.id
    })
  })
}
getGoodsSelect()

// 付款金额类型
let paymentAmountTypeArr: any = reactive([])
const getPayTypeListFn = async () => {
  let res: any = await getPayTypeList({})
  for (let key in res.data) {
    paymentAmountTypeArr.push({
      label: res.data[key],
      value: key
    })
  }
}
getPayTypeListFn()

//货物位置
const locationOfGoodsArr: any = reactive([])
const getStoreSelect = async () => {
  let res: any = await storeSelect({})
  res.data.list.forEach((item) => {
    locationOfGoodsArr.push({
      label: item.name,
      value: item.id
    })
  })
}
getStoreSelect()

// 运输方式
const modeOfTransportArr: any = reactive([])
const getTransportSelect = async () => {
  let res: any = await transportSelect({})
  res.data.list.forEach((item) => {
    modeOfTransportArr.push({
      label: item.name,
      value: item.name
    })
  })
}
getTransportSelect()

//始发地
const originArr: any = reactive([])
const getOriginSelect = async () => {
  let res: any = await placestartSelect({})
  res.data.list.forEach((item) => {
    originArr.push({
      label: item.name,
      value: item.name
    })
  })
}
getOriginSelect()
//关联客户
const relatedCustomersArr: any = reactive([])
const getClientSelect = async () => {
  let res: any = await clientSelect({})
  res.data.list.forEach((item) => {
    relatedCustomersArr.push({
      label: item.code,
      value: item.code
    })
  })
}
getClientSelect()

//收件人
const consigneeArr: any = reactive([])
const getConsigneeSelect = async () => {
  let res: any = await consigneeSelect({})
  console.log('---收件人下拉选择---', res)
  res.data.list.forEach((item) => {
    consigneeArr.push({
      label: item.cilent_id,
      value: item.cilent_id
    })
  })
}
getConsigneeSelect()

//目的地
const placeendArr: any = reactive([])
const getPlaceendSelect = async () => {
  let res: any = await placeendSelect({})
  console.log('---目的地下拉选择---', res)
  res.data.list.forEach((item) => {
    placeendArr.push({
      label: item.name,
      value: item.name
    })
  })
}
getPlaceendSelect()
const rkNumInput = () => {
  form.pieceArray = []
  if (form.warehousingItems) {
    for (let i = 1; i <= form.warehousingItems; i++) {
      let pieceItem = reactive({
        key: i,
        title: `${t('warehousingEntryAddWrite.goodsEntry')} ${i} ：`,
        gname: '', // 名称
        goods_id: '', // 货物种类
        worth: '', // 单件货值
        total1: '',
        total: '',
        list: [
          {
            piece: '',
            quantity: '',
            room: '',
            colour: '',
            length: '',
            width: '',
            high: '',
            weight: '',
            remark: '',
            price: '',
            size: ''
          }
        ]
      })
      form.pieceArray.push(pieceItem)
    }
  } else {
    form.pieceArray = []
  }

  console.log('---form.pieceArray---', form.pieceArray)
}

// const addGoods = (pIndex) => {
//   let goodsItem = {
//     shopNum: '',
//     bz: '',
//     num: '',
//     home: '',
//     color: '',
//     long: '',
//     wide: '',
//     tall: '',
//     weight: ''
//   }
//   form.pieceArray[pIndex].list.push(goodsItem)
// }
// const delGoods = (pIndex, index) => {
//   form.pieceArray[pIndex].list.splice(index, 1)
// }

defineExpose({
  getFormData: () => {
    return form
  }
})
const totalSUM = () => {
  let total = 0 //总合计
  let total_sale = 0 //销售总价格
  for (let a = 0; a < form.pieceArray.length; a++) {
    form.pieceArray[a].total1 = (
      form.pieceArray[a].worth *
      form.pieceArray[a].piece *
      form.pieceArray[a].quantity
    ).toFixed(2)
    form.pieceArray[a].total = form.pieceArray[a].piece * form.pieceArray[a].quantity
    total += Number(form.pieceArray[a].total1)
    form.pieceArray[a].total_sale = (
      (form.pieceArray[a].price ? form.pieceArray[a].price : 0) *
      form.pieceArray[a].piece *
      form.pieceArray[a].quantity
    ).toFixed(2)
    total_sale += Number(form.pieceArray[a].total_sale)
  }

  form.value = Number(total + Number(form.freight_receive) - Number(form.moling ? form.moling : 0)) //采购总价
  form.pricerebate = form.value * form.rebate * 0.01 //工厂
  form.priceValue =
    total_sale + Number(form.freight_receive) - Number(form.moling ? form.moling : 0) //销售总价
  console.log(form.priceValue, '销售总价')
  form.priceDifferenceOfGoods = (
    Number(form.priceValue) -
    Number(form.value) +
    Number(form.freight_receive) -
    Number(form.collectionOfFreight)
  ).toFixed(2)
  form.priceservicefee = form.priceValue * form.servicefee * 0.01 //服务费用
  form.priceValue += form.priceservicefee //最终销售总价
  form.priceValue = form.priceValue + form.priceValue * Number(form.taxRate) * 0.01 //最终销售总价*税率
  // console.log(form.value, 'value')
}
</script>

<template>
  <ElForm :model="form" label-width="auto">
    <ElRow>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntry.typeOfGoods')">
          <ElSelect
            disabled
            v-model="form.typeOfGoods"
            :placeholder="t('alertEn.PleaseSelectThetypeOfGoods')"
          >
            <ElOption
              v-for="item in typeOfGoodsArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntry.locationOfGoods')">
          <ElSelect
            disabled
            v-model="form.locationOfGoods"
            :placeholder="t('alertEn.PleaseSelectThelocationOfGoods')"
          >
            <ElOption
              v-for="item in locationOfGoodsArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntryAddWrite.modeOfTransport')">
          <ElSelect
            disabled
            v-model="form.modeOfTransport"
            :placeholder="t('alertEn.PleaseSelectThemodeOfTransport')"
            filterable
          >
            <ElOption
              v-for="(item, index) in modeOfTransportArr"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('router.origin')">
          <ElSelect
            disabled
            v-model="form.origin"
            :placeholder="t('alertEn.PleaseSelectTheorigin')"
          >
            <ElOption
              v-for="item in originArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
    </ElRow>
    <ElRow>
      <ElCol :span="6">
        <ElFormItem disabled label-width="100px" label="客户号">
          <ElSelect v-model="form.relatedCustomers" :placeholder="t('common.inputText')" disabled>
            <ElOption
              v-for="item in relatedCustomersArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntry.paymentType')">
          <ElSelect
            disabled
            v-model="form.paymentAmountType"
            :placeholder="t('alertEn.PleaseSelectPaymentType')"
          >
            <ElOption
              v-for="item in paymentAmountTypeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntryAddWrite.warehousingTime')">
          <ElDatePicker
            disabled
            v-model="form.warehousingTime"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="t('alertEn.PleaseSelectTheStorageTime')"
            :shortcuts="[
              {
                text: '今天',
                value: new Date()
              }
            ]"
          />
        </ElFormItem>
      </ElCol>
    </ElRow>
    <ElRow>
      <ElCol :span="6">
        <ElFormItem label-width="100px" label="采购总合计">
          <ElInput v-model="form.value" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntryAddWrite.serviceCharge')">
          <ElInput v-model="form.servicefee" @blur="totalSUM">
            <template #append>%</template>
          </ElInput>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" label="代付运费">
          <ElInput v-model="form.collectionOfFreight" @blur="totalSUM" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" label="应收运费">
          <ElInput v-model="form.freight_receive" @blur="totalSUM" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntryAddWrite.factoryRebate')">
          <ElInput v-model="form.rebate" disabled>
            <template #append>%</template>
          </ElInput>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem
          label-width="100px"
          :label="t('warehousingEntryAddWrite.priceDifferenceOfGoods')"
        >
          <ElInput v-model="form.priceDifferenceOfGoods" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntry.productNameRemarks')">
          <ElInput v-model="form.productNameRemarks" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('purchaseOrderAddWrite.recipient')">
          <ElSelect v-model="form.recipient" :placeholder="t('common.selectText')" disabled>
            <ElOption
              v-for="item in consigneeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntry.destination')" disabled>
          <ElSelect v-model="form.destination" :placeholder="t('common.selectText')" disabled>
            <ElOption
              v-for="item in placeendArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('shippingOrderSettings.taxRate')">
          <ElInput v-model="form.taxRate" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" :label="t('warehousingEntryAddWrite.warehousingItems')">
          <ElInput v-model="form.warehousingItems" @input="rkNumInput" disabled />
        </ElFormItem>
      </ElCol>
    </ElRow>
    <ElDivider>销售统计</ElDivider>
    <ElRow>
      <ElCol :span="6">
        <ElFormItem label-width="100px" label="销售总合计">
          <ElInput v-model="form.priceValue" disabled />
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" label="服务费">
          <ElInput v-model="form.priceservicefee" disabled>
            <template #append>￥</template></ElInput
          >
        </ElFormItem>
      </ElCol>
      <ElCol :span="6">
        <ElFormItem label-width="100px" label="工厂返点金额">
          <ElInput v-model="form.pricerebate" disabled>
            <template #append>￥</template>
          </ElInput>
        </ElFormItem>
      </ElCol>
    </ElRow>
    <ElDivider />
    <ElRow v-for="(vforPieceItem, index) in form.pieceArray" :key="index">
      <ElCol :span="24">
        <ElRow class="listForItem">
          <ElCol :span="1">
            <ElDivider />
          </ElCol>
          <ElCol :span="4">{{ vforPieceItem.title }}</ElCol>
          <ElCol :span="4">
            <ElFormItem :label="t('warehousingEntry.typeOfGoods')">
              <ElSelect
                disabled
                v-model="vforPieceItem.goods_id"
                :placeholder="t('alertEn.PleaseSelectThetypeOfGoods')"
              >
                <ElOption
                  v-for="item in typeOfGoodsArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="7">
            <ElFormItem :label="t('warehousingEntryAddWrite.name')">
              <ElInput v-model="vforPieceItem.gname" disabled />
            </ElFormItem>
          </ElCol>

          <ElCol :span="1">
            <ElDivider />
          </ElCol>
        </ElRow>
      </ElCol>
      <ElCol :span="24">
        <ElRow>
          <ElCol :span="3">
            <ElFormItem label-width="60px" :label="t('warehousingEntryAddWrite.numberOfPieces')">
              <ElInput v-model="vforPieceItem.piece" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" label="装箱数">
              <ElInput v-model="vforPieceItem.quantity" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" label="总数量">
              <ElInput v-model="vforPieceItem.total" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" :label="t('purchaseOrderAddWrite.roomNo')">
              <ElInput v-model="vforPieceItem.room" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" :label="t('purchaseOrderAddWrite.color')">
              <ElInput v-model="vforPieceItem.colour" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" :label="t('purchaseOrderAddWrite.long')">
              <ElInput v-model="vforPieceItem.length" disabled
                ><template #append>m</template></ElInput
              >
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" :label="t('purchaseOrderAddWrite.wide')">
              <ElInput v-model="vforPieceItem.width" disabled
                ><template #append>m</template></ElInput
              >
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" :label="t('purchaseOrderAddWrite.tall')">
              <ElInput v-model="vforPieceItem.high" disabled
                ><template #append>m</template></ElInput
              >
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="60px" :label="t('purchaseOrderAddWrite.weight')">
              <ElInput v-model="vforPieceItem.weight" disabled
                ><template #append>KG</template></ElInput
              >
            </ElFormItem>
          </ElCol>
          <ElRow />

          <ElCol :span="3">
            <ElFormItem label-width="60px" label="尺寸">
              <ElInput v-model="vforPieceItem.size"><template #append>m</template></ElInput>
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label="采购单价">
              <ElInput v-model="vforPieceItem.worth" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label="采购合计">
              <ElInput v-model="vforPieceItem.total1" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="80px" label="销售单价">
              <ElInput v-model="vforPieceItem.price" @blur="totalSUM" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="3">
            <ElFormItem label-width="80px" label="销售合计">
              <ElInput v-model="vforPieceItem.total_sale" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="8">
            <ElFormItem label-width="60px" :label="t('purchaseOrderAddWrite.notes')">
              <ElInput v-model="vforPieceItem.remark" />
            </ElFormItem>
          </ElCol>

          <!-- <ElCol :span="1" :offset="1">
            <ElButton
              v-if="j == vforPieceItem.list.length - 1"
              type="primary"
              :icon="addIcon"
              circle
              @click="addGoods(index)"
            />
            <ElButton v-else type="danger" :icon="delIcon" circle @click="delGoods(index, j)" />
          </ElCol> -->
        </ElRow>
      </ElCol>
    </ElRow>
  </ElForm>
</template>
<style scoped lang="less">
.listForItem {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .el-col:nth-of-type(2) {
    font-size: var(--el-form-label-font-size);
    padding: 0 15px;
  }
  .el-col:nth-of-type(1) {
    padding-right: 15px;
  }
  .el-col:nth-of-type(6) {
    padding-left: 15px;
  }
  .el-divider--horizontal {
    margin: 0;
  }
  .el-form-item--default {
    margin-bottom: 0;
  }
}
</style>
